package mspbots.autotask.data.core.contractbillingrules;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractBillingRulesReceiver {
    private final ContractBillingRulesRepository contractBillingRulesRepository;

//    @RabbitListener(queues = "auto-task.contract-billing-rules.sync")
    public void syncTask(ResultMsg content) {

        ContractBillingRule contractBillingRule = ContractBillingRule.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(contractBillingRule.getOtherId())){
            return;
        }

        this.contractBillingRulesRepository.findByOtherIdAndTenantId(content.getId(),content.getTenantId())
                .map(oldAdditionalInvoiceFieldValue -> {
                    contractBillingRule.setId(oldAdditionalInvoiceFieldValue.getId());
                    return contractBillingRule;
                })
                .defaultIfEmpty(contractBillingRule)
                .flatMap(this.contractBillingRulesRepository::save).block(Duration.ofSeconds(10));

    }
}
